﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp3
{
    /// <summary>
    /// 实现事件总线：接下来，我们来实现这个接口。这里我们可以使用一个字典来存储事件类型和对应的处理函数。
    /// </summary>
    public class EventBus : IEventBus
    {
        private readonly Dictionary<Type, List<Delegate>> _eventHandlers = new();

        public void Publish<TEvent>(TEvent eventData)
        {
            if (_eventHandlers.ContainsKey(typeof(TEvent)))
            {
                foreach (var handler in _eventHandlers[typeof(TEvent)])
                {
                    var typedHandler = (Action<TEvent>)handler;
                    typedHandler(eventData);
                }
            }
        }

        public void Subscribe<TEvent>(Action<TEvent> eventHandler)
        {
            if (!_eventHandlers.ContainsKey(typeof(TEvent)))
            {
                _eventHandlers[typeof(TEvent)] = new List<Delegate>();
            }
            _eventHandlers[typeof(TEvent)].Add(eventHandler);
        }

        public void Unsubscribe<TEvent>(Action<TEvent> eventHandler)
        {
            if (_eventHandlers.ContainsKey(typeof(TEvent)))
            {
                _eventHandlers[typeof(TEvent)].Remove(eventHandler);
            }
        }
    }
}
